<template>
  <div class="forgot-password-page">
    <h2 class="page-title">{{ $t('auth.forgotPassword.title') }}</h2>
    <p class="page-subtitle">{{ $t('auth.forgotPassword.subtitle') }}</p>
    
    <el-form
      ref="formRef"
      :model="forgotForm"
      :rules="rules"
      label-position="top"
      size="large"
    >
      <el-form-item :label="$t('auth.forgotPassword.email')" prop="email">
        <el-input
          v-model="forgotForm.email"
          type="email"
          :placeholder="$t('auth.forgotPassword.email')"
          prefix-icon="Message"
          :disabled="codeSent"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button
          v-if="!codeSent"
          type="primary"
          size="large"
          style="width: 100%"
          :loading="loading"
          :disabled="isSubmitting"
          @click="handleSendCode"
        >
          {{ isSubmitting ? '发送中...' : $t('auth.forgotPassword.sendCode') }}
        </el-button>
        
        <div v-else class="code-sent-info">
          <el-alert
            :title="$t('auth.forgotPassword.codeSent')"
            type="success"
            :closable="false"
            show-icon
          />
          
          <div class="resend-section">
            <el-button
              v-if="canResend"
              type="primary"
              plain
              size="large"
              style="width: 100%"
              :loading="loading"
              @click="handleResendCode"
            >
              {{ $t('auth.forgotPassword.resendCode') }}
            </el-button>
            
            <p v-else class="countdown-text">
              {{ countdown }} {{ $t('auth.forgotPassword.resendIn') }}
            </p>
          </div>
          
          <el-button
            type="success"
            size="large"
            style="width: 100%; margin-top: 16px"
            @click="goToResetPassword"
          >
            下一步：重置密码
          </el-button>
        </div>
      </el-form-item>
    </el-form>
    
    <div class="auth-switch">
      <router-link to="/auth/login" class="back-link">
        <el-icon><ArrowLeft /></el-icon>
        {{ $t('auth.forgotPassword.backToLogin') }}
      </router-link>
    </div>
    
    <!-- 开发环境提示 -->
    <div v-if="isDev && verificationCode" class="dev-tip">
      <el-alert
        title="开发环境提示"
        type="warning"
        :closable="false"
        show-icon
      >
        <p>验证码: <strong>{{ verificationCode }}</strong></p>
        <p>请在重置密码页面使用此验证码</p>
      </el-alert>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import type { ForgotPasswordForm } from '@/types'

const router = useRouter()
const userStore = useUserStore()

// 表单引用
const formRef = ref<FormInstance>()
const loading = ref(false)
const codeSent = ref(false)
const verificationCode = ref('')

// 重发倒计时
const countdown = ref(60)
const canResend = computed(() => countdown.value <= 0)

// 开发环境标识
const isDev = computed(() => import.meta.env.DEV)

// 表单数据
const forgotForm = reactive<ForgotPasswordForm>({
  email: ''
})

// 表单验证规则
const rules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 防抖处理
const isSubmitting = ref(false)

/**
 * 开始倒计时
 */
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

/**
 * 发送验证码
 */
const handleSendCode = async () => {
  if (!formRef.value || isSubmitting.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    isSubmitting.value = true
    loading.value = true

    const result = await userStore.sendPasswordResetCode(forgotForm.email)

    if (result.success) {
      ElMessage({
        message: result.message,
        type: 'success',
        duration: 3000,
        showClose: true
      })

      codeSent.value = true
      verificationCode.value = result.code || ''
      startCountdown()
    } else {
      ElMessage({
        message: result.message,
        type: 'error',
        duration: 3000,
        showClose: true
      })
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage({
      message: '发送验证码失败，请重试',
      type: 'error',
      duration: 3000,
      showClose: true
    })
  } finally {
    loading.value = false
    setTimeout(() => {
      isSubmitting.value = false
    }, 1000)
  }
}

/**
 * 重新发送验证码
 */
const handleResendCode = async () => {
  await handleSendCode()
}

/**
 * 跳转到重置密码页面
 */
const goToResetPassword = () => {
  router.push({
    path: '/auth/reset-password',
    query: {
      email: forgotForm.email
    }
  })
}
</script>

<style lang="scss" scoped>
.forgot-password-page {
  .page-title {
    text-align: center;
    font-size: var(--font-size-2xl);
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: var(--spacing-md);
  }
  
  .page-subtitle {
    text-align: center;
    color: var(--text-secondary);
    margin-bottom: var(--spacing-2xl);
    line-height: 1.6;
  }
  
  .code-sent-info {
    width: 100%;
    
    .resend-section {
      margin-top: var(--spacing-lg);
      
      .countdown-text {
        text-align: center;
        color: var(--text-secondary);
        font-size: var(--font-size-sm);
        margin: var(--spacing-md) 0;
      }
    }
  }
  
  .auth-switch {
    text-align: center;
    margin-top: var(--spacing-lg);
    
    .back-link {
      color: var(--primary-color);
      text-decoration: none;
      display: inline-flex;
      align-items: center;
      gap: var(--spacing-xs);
      
      &:hover {
        color: var(--primary-dark);
      }
    }
  }
  
  .dev-tip {
    margin-top: var(--spacing-xl);
    
    :deep(.el-alert__content) {
      p {
        margin: var(--spacing-xs) 0;
        font-size: var(--font-size-sm);
        
        strong {
          color: var(--warning-color);
          font-family: 'Courier New', monospace;
          font-size: var(--font-size-lg);
        }
      }
    }
  }
}
</style> 